<template>
  <el-dialog v-model="addOrEditVisible" title="菜单管理" :before-close="closeEditDialog" width="50%">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="160px" class="demo-ruleForm"
             :size="formSize" status-icon>
      <el-row>
        <el-col :span="24">
          <el-form-item label="菜单类型" prop="menuType">
            <el-radio-group v-model="ruleForm.menuType" class="ml-4">
              <el-radio :label=0 size="large" checked>目录</el-radio>
              <el-radio :label=1 size="large">菜单</el-radio>
<!--              <el-radio :label=2 size="large">按钮</el-radio>-->
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="ruleForm.menuType == 0 || ruleForm.menuType == 1 || ruleForm.menuType == 2">
        <el-col :span="24">
          <el-form-item label="上级菜单" prop="parentId">
            <el-cascader v-model="ruleForm.parentId" :options="menuTree" :props="defaultMenuTreeProps" style="width: 100%"
                         :show-all-levels="true" placeholder="请选择上级菜单" @change="parentMenuChange" filterable clearable />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ruleForm.menuType == 0 || ruleForm.menuType == 1 || ruleForm.menuType == 2">
        <el-col :span="24">
          <el-form-item label="菜单名称" prop="title">
            <el-input v-model="ruleForm.title"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ruleForm.menuType == 0 || ruleForm.menuType == 1">
        <el-col :span="24">
          <el-form-item label="菜单图标" prop="icon">
            <el-button :icon="ruleForm.icon" size="large" @click="loadIcons('System')"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row v-if="ruleForm.menuType == 1">
        <el-col :span="24">
          <el-form-item label="路由地址" prop="path">
            <el-input v-model="ruleForm.path"/>
            <span class="form-tip">访问的路由地址，如：`/user`，如外网地址需内链访问则以`http(s)://`开头</span>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="ruleForm.menuType == 0 || ruleForm.menuType == 1 || ruleForm.menuType == 2">
        <el-col :span="24">
          <el-form-item label="菜单排序" prop="menuSort">
            <el-input-number v-model="ruleForm.menuSort" :min="1" :max="20"/>
          </el-form-item>
        </el-col>
      </el-row>

      <el-row v-if="ruleForm.menuType == 0 || ruleForm.menuType == 1 || ruleForm.menuType == 2">
        <el-col :span="24">
          <el-form-item label="状态" prop="statusFlag">
            <el-radio-group v-model="ruleForm.statusFlag" class="ml-4">
              <el-radio v-for="(status,index) in STATUS_LIST" :label=status.label size="large">{{status.text}}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
<!--      <el-row v-if="ruleForm.menuType == 0 || ruleForm.menuType == 1">-->
<!--        <el-col :span="24">-->
<!--          <el-form-item label="是否显示删除" prop="tabShowDelFlag">-->
<!--            <el-radio-group v-model="ruleForm.tabShowDelFlag" class="ml-4">-->
<!--              <el-radio v-for="(status,index) in YES_NO_LIST" :label=status.label size="large">{{status.text}}</el-radio>-->
<!--            </el-radio-group>-->
<!--            <div class="form-tip">在顶部切换是否显示删除图标</div>-->
<!--          </el-form-item>-->

<!--        </el-col>-->
<!--      </el-row>-->
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeEditDialog">关闭</el-button>
        <el-button type="primary" @click="submitForm(ruleFormRef)">提交</el-button>
      </span>
    </template>
  </el-dialog>

  <el-dialog
      v-model="iconDialogVisible"
      :before-close="handleIconsClose"
      title="菜单图标"
      width="50%"
      align-center>
    <el-tabs v-model="iconActiveName" class="demo-tabs" @tab-click="iconTabsHandleClick">
      <el-tab-pane v-for="tab in tabs" :label="tab.name" :name="tab.value">
        <ul class="demo-icon-list">
        <li class="icon-item" v-for="icon in icons" @click="iconMenuSignalBtnClick(icon)">
          <span class="demo-svg-icon">
            <i class="el-icon" style="font-size: 20px;">
              <svg viewBox="0 0 1024 1024" xmlns="http://www.w3.org/2000/svg">
                <component :is="icon.icon"/>
              </svg>
            </i>
            <span class="icon-name" data-v-029747aa="">{{ icon.icon }}</span>
          </span>
        </li>
      </ul>
      </el-tab-pane>
    </el-tabs>
  </el-dialog>
</template>

<script lang="ts" setup>
import {reactive, ref, onMounted, watch} from 'vue'
import type {FormInstance, FormRules} from 'element-plus'
import {Menu} from '@/apis/model/system/MenuModel';
import {insertMenu, menuLoop, updateMenu} from "@/apis/http/system/MenuHttp";
import {ElMessage} from "element-plus";
import router from "@/router";
import {iconPage} from "@/apis/http/system/IconHttp";
import {ICon} from "@/apis/model/system/IconModel";
import {Params} from "@/apis/model/common/common.interfaces";
import {STATUS_LIST, YES_NO_LIST} from '@/util/common.util';
import type { TabsPaneContext } from 'element-plus'

interface Prop {
  addOrEditVisible: boolean,
  ruleForm: Menu,
  addDataType: string
}

const tabs = ref([{value:'System',name: '系统'},{value:'Arrow', name: '方向'},{value:'Document',name: '文档'},{value:'Media',name: '媒体'},{value:'Traffic',name:'交通'},{value:'Food', name:'水果'},{value:'Items',name:'类目'},{value:'Weather',name: '天气'},{value:'Other',name: '其他'}]);
// 图片激活
const iconActiveName = ref('System');

// 刷新list页面
const refushList = ref(false);

const iconDialogVisible = ref(false)


// 传递过来的参数
const props = defineProps<Prop>();

const emit = defineEmits(["closeEditDialog"]);

const parentMenus = ref([] as Array<Menu>)
const icons = ref([] as Array<ICon>)

const parentMenusProps = {
  expandTrigger: 'click',
  multiple: false,
  value: 'id',
  label: 'title',
  children: 'children',
  checkStrictly: true
}

/**
 * 获取数据
 * @param value json类型的数据
 */
const parentMenuChange = (value: any) => {
  if (value == null) {
    props.ruleForm.parentId = -1;
    return;
  }

  for (var i = 0; i < 10; i++) {
    if (value[i] == undefined) {
      props.ruleForm.parentId = value[i - 1]
      break;
    }
  }
}

// 关闭按钮
const closeEditDialog = () => {
  emit("closeEditDialog", {
    addOrEditVisible: !props.addOrEditVisible,
    refushList: refushList.value
  })
}
const formSize = ref('default')
const ruleFormRef = ref<FormInstance>()
const rules = reactive<FormRules>({
  name: [
    {required: true, message: '请输入菜单名称（英文）', trigger: 'blur'}
  ],
  title: [
    {required: true, message: '请输入菜单名称', trigger: 'blur'}
  ],
  icon: [
    {required: true, message: '请输入菜单图标', trigger: 'blur'}
  ],
  menuSort: [
    {required: true, message: '请输入菜单排序', trigger: 'blur'}
  ],
  // parentId: [
  //   { required: true, message: '请输入父菜单', trigger: 'blur' }
  // ],
  statusFlag: [
    {required: true, message: '请输入菜单状态', trigger: 'blur'}
  ],
  menuType: [
    {required: true, message: '请输入菜单类型', trigger: 'blur'}
  ],
  tabShowDelFlag: [
    {required: true, message: '请输入Tabs删除标志', trigger: 'blur'}
  ],
})

/**
 * tabs切换
 */
const iconTabsHandleClick = (tab: TabsPaneContext, event: Event) =>{
  debugger
  console.log(tab)
  console.log(event)
  loadIcons(tab.paneName);
}

const loadIcons = (val: any) => {
  let param = {
    current: 1,
    size: 100,
    search: '',
    entity: {
      category: val
    } as ICon
  } as Params;
  iconPage(param).then(res => {
    const code = res.code
    const message = res.message
    const data = res.data.list as Array<ICon>
    if (code == 200) {
      icons.value = data
    }
  })
  iconDialogVisible.value = true
}

const handleIconsClose = () =>{
   iconActiveName.value = 'System'
  iconDialogVisible.value = false
}

const menuTree = ref([] as Array<Menu>);

const defaultMenuTreeProps = {
  expandTrigger: 'click',
  children: 'children',
  multiple: false,
  checkStrictly: true,
  label: 'title',
  value: 'id'
}
watch(() => props.addOrEditVisible, ()=>{
  if (props.addOrEditVisible == true) {
    menuLoop({statusFlag: 1}).then(res=>{
      menuTree.value = res.data
    });
  }
})

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return
  await formEl.validate((valid, fields) => {
    if (valid) {
      // 新增
      if (props.addDataType === 'add') {
        insertMenu(props.ruleForm).then(res => {
          const code = res.code;
          const message: string = res.message;
          const data = res.data;
          if (code == 200) {
            ElMessage({
              message: '添加数据成功',
              type: 'success',
            })
            refushList.value = true
            closeEditDialog()
          }
        })
      } else if (props.addDataType === 'edit') {
        updateMenu(props.ruleForm).then(res => {
          const code = res.code;
          const message: string = res.message;
          const data = res.data;
          if (code == 200) {
            ElMessage({
              message: '更新数据成功',
              type: 'success',
            })
            refushList.value = true
            closeEditDialog()
          }
        })
      }
    } else {
      console.log('error submit!', fields)
    }
  })
}

const iconMenuSignalBtnClick = (icon: ICon) => {
  props.ruleForm.icon = icon.icon;
  iconDialogVisible.value = false;
  iconActiveName.value = 'System'
}

/**
 * 菜单列表
 */
onMounted(() => {
  menuLoop({}).then(res => {
    const code = res.code
    const message = res.message
    const data = res.data as Array<Menu>
    if (code == 200) {
      parentMenus.value = data;
    }
  });
})
</script>

<style scoped>
.dialog-footer button:first-child {
  margin-right: 10px;
}

.form-tip {
  color: gray;
}

::v-deep .el-cascader__tags .el-cascader__search-input {
  min-width: 0;
}

.el-select {
  width: 100%;
}


.demo-icon-list {
  overflow: hidden;
  list-style: none;
  padding: 0 !important;
  border-top: 1px solid var(--el-border-color);
  border-left: 1px solid var(--el-border-color);
  border-radius: 4px;
  display: grid;
  grid-template-columns: repeat(7, 1fr);
}

.demo-icon-list .icon-item {
  text-align: center;
  color: var(--el-text-color-regular);
  height: 90px;
  font-size: 13px;
  border-right: 1px solid var(--el-border-color);
  border-bottom: 1px solid var(--el-border-color);
  transition: background-color var(--el-transition-duration);
}

.demo-icon-list .icon-item .demo-svg-icon {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  cursor: pointer;
}

ul, ol {
  padding-left: 1.25em;
}

p, ol, ul {
  margin: 1rem 0;
  line-height: 1.7;
}
</style>
